<?php
/**
 * Author: xx.com
 * Date: 2019-9-5
 */
namespace Admin\Controller;

use Think\AjaxPage;
use Admin\Logic\IntegralOrderLogic;
use Think\Page;

class IntegralController extends BaseController
{
    public  $order_status;
    public  $pay_status;
    public  $shipping_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        // 订单 支付 发货状态
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }

    /**
     *  积分商品分类列表
     */
    public function categoryList()
    {
        $integral_goods_category = M('integral_goods_category')->order('id asc')->select();

        $this->assign('cat_list', $integral_goods_category);
        $this->display();
    }

    /**
     *  积分商品标签列表
     */
    public function labelList()
    {
        $integral_goods_category = M('integral_label')->order('id asc')->select();

        $this->assign('cat_list', $integral_goods_category);
        $this->display();
    }

    /**
     * 添加修改商品分类
     */
    public function addEditCategory()
    {

        // \var_dump($shop);
        if (IS_GET) {
            $cate_id = I('GET.id', 0);

            if ($cate_id) {
                $goods_category_info = M('integral_goods_category')->where([
                    'id' => $cate_id
                ])->find();

                if (! $goods_category_info) {
                    return $this->error('未找到相关分类');
                }
            }

            $this->assign('goods_category_info', $goods_category_info);
            $this->display('_category');
            exit;
        }

        $GoodsCategory = D('IntegralGoodsCategory'); //

        $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if ($_GET['is_ajax'] == 1) {
            C('TOKEN_ON', false);

            if (!$GoodsCategory->create(null, $type)) {// 根据表单提交的POST数据创建数据对象
                //  编辑
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '操作失败!',
                    'data'  => $GoodsCategory->getError(),
                );
                $this->ajaxReturn(json_encode($return_arr));
            } else {
                //  form表单提交
                C('TOKEN_ON', true);

                if ($type == 2) {
                    $GoodsCategory->save(); // 写入数据到数据库
                } else {
                    $insert_id = $GoodsCategory->add(); // 写入数据到数据库
                }
                $return_arr = array(
                    'status' => 1,
                    'msg'   => '操作成功',
                    'data'  => array('url'=>U('Admin/Integral/categoryList')),
                );
                $this->ajaxReturn($return_arr);
            }
        }
    }

    /**
     * 添加修改商品标签
     */
    public function addEditLabel()
    {

        // \var_dump($shop);
        if (IS_GET) {
            $cate_id = I('GET.id', 0);

            if ($cate_id) {
                $goods_label_info = M('integral_label')->where([
                    'id' => $cate_id
                ])->find();

                if (! $goods_label_info) {
                    return $this->error('未找到相关标签');
                }
            }

            $this->assign('goods_label_info', $goods_label_info);
            $this->display('_label');
            exit;
        }

        $GoodsLabel = D('IntegralLabel'); //

        $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if ($_GET['is_ajax'] == 1) {
            C('TOKEN_ON', false);

            if (!$GoodsLabel->create(null, $type)) {// 根据表单提交的POST数据创建数据对象
                //  编辑
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '操作失败!',
                    'data'  => $GoodsLabel->getError(),
                );
                $this->ajaxReturn(json_encode($return_arr));
            } else {
                //  form表单提交
                C('TOKEN_ON', true);

                if ($type == 2) {
                    $GoodsLabel ->save(); // 写入数据到数据库
                } else {
                    $insert_id = $GoodsLabel ->add(); // 写入数据到数据库
                }
                $return_arr = array(
                    'status' => 1,
                    'msg'   => '操作成功',
                    'data'  => array('url'=>U('Admin/Integral/labelList')),
                );
                $this->ajaxReturn($return_arr);
            }
        }
    }

    /**
     * 删除分类
     */
    public function delGoodsCategory()
    {
        // 判断是否存在商品
        $GoodsCategory = D('IntegralGoodsCategory');
        $goods_count = M('integral_goods')->where("cat_id = {$_GET['id']}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不得删除!', U('Admin/Integral/categoryList'));
        // 删除分类
        $GoodsCategory->where("id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Integral/categoryList'));
    }

    /**
     * 删除标签
     */
    public function delGoodsLabel()
    {
        $GoodsLabel = D('IntegralLabel');
        // 删除分类
        $GoodsLabel ->where("id = {$_GET['id']}")->delete();
        M('integral_goods_label')->where(['integral_label_id'=>$_GET['id']])->delete();
        $this->success("操作成功!!!", U('Admin/Integral/labelList'));
    }


    /**
     *  商品列表
     */
    public function goodsList()
    {
        $where_integral_goods_category['is_show'] = 1;
        $integral_goods_category = M('integral_goods_category')->where($where_integral_goods_category)->order('id asc')->select();
        $this->assign('categoryList', $integral_goods_category);
        $this->display();
    }

    /**
     *  商品列表
     */
    public function ajaxGoodsList()
    {
        $where = ' 1 = 1 '; // 搜索条件
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale') ;
        $cat_id = I('cat_id');
        // 关键词搜索
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if ($key_word) {
            $where = "$where and (goods_name like '%$key_word%')" ;
        }

        if ($cat_id > 0) {
            $where .= " and cat_id =".$grandson_ids; // 初始化搜索条件
        }


        $model = M('integral_goods');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        /**  搜索条件下 分页赋值
         * foreach($condition as $key=>$val) {
         * $Page->parameter[$key]   =   urlencode($val);
         * }
         */
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $where_integral_goods_category['is_show'] = 1;
        $integral_goods_category = M('integral_goods_category')->where($where_integral_goods_category)->order('id asc')->select();
        $catList = [];
        foreach ($integral_goods_category as $k => $v) {
            $catList[$v['id']] = $v;
        }
        // p( $integral_goods_category);die;
        $this->assign('catList', $catList);
        $this->assign('goodsList', $goodsList);
        $this->assign('page', $show);// 赋值分页输出
        $this->display();
    }


    /**
     * 添加修改商品
     */
    public function addEditGoods()
    {
        $Goods = D('IntegralGoods'); //
        $type = $_POST['goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if (($_GET['is_ajax'] == 1) && IS_POST) {
            C('TOKEN_ON', false);
            if (!$Goods->create(null, $type)) {// 根据表单提交的POST数据创建数据对象
                //  编辑
                $error = $Goods->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn(json_encode($return_arr));
            } else {
                //获取当前登录人的信息
                //  form表单提交
                //              C('TOKEN_ON',true);
                // p($_POST);die;

                if ($type == 2) {
                    $goods_id = $_POST['goods_id'];

                    $goodsInfo = M('integral_goods')->where([
                        "goods_id" => $goods_id
                    ])->field("goods_id")->find();

                    if (!$goodsInfo) {
                        return $this->error("商品不存在");
                    }


                    $Goods->save(); // 写入数据到数据库
                } else {
                    $goods_id = $insert_id = $Goods->add(); // 写入数据到数据库
                }
                // 删除所有的标签
                $where_goods_label_delete['integral_goods_id'] = $goods_id;
                M('integral_goods_label')->where($where_goods_label_delete)->delete();
                foreach ($_POST['label_list'] as $k => $v) {
                    if ($v) {
                        $where_goods_label_delete['integral_label_id'] = $v;
                        M('integral_goods_label')->where($where_goods_label_delete)->add($where_goods_label_delete);
                    }
                }
                $return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Integral/goodsList')),
                );
                $this->ajaxReturn($return_arr);
            }
        }

        $goodsInfo = M('integral_goods')->where('goods_id=' . I('GET.id', 0))->find();

        $cat_list = M('integral_goods_category')->order('sort_order DESC')->select();
        $label_list = M('integral_label')->order('sort_order DESC')->select();
        foreach ($label_list as $k => &$v) {
            $v['is_check'] = 0;
            if ($goodsInfo) {
                $where_goods_label['integral_goods_id'] = $goodsInfo['goods_id'];
                $where_goods_label['integral_label_id'] = $v['id'];
                if (M('integral_goods_label')->where($where_goods_label)->find()) {
                    $v['is_check'] = 1;
                }
            }
        }

        $this->assign('cat_list', $cat_list);
        $this->assign('label_list', $label_list);
        $this->assign('goodsInfo', $goodsInfo);  // 商品详情
        $this->initEditor(); // 编辑器
        $this->display('_goods');
    }



    /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';

        $goodsInfo = M("integral_goods")->where('goods_id ='.$goods_id)->find();

        if (!$goodsInfo) {
            $this->returnInfo(-1, "商品不存在");
        }

        // 判断此商品是否有订单
        $c1 = M('integral_order')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';


        if ($error) {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
            $this->ajaxReturn(json_encode($return_arr));
        }

        // 删除此商品
        M("integral_goods")->where('goods_id ='.$goods_id)->delete();  //商品表
        M("integral_goods_label")->where('integral_goods_id ='.$goods_id)->delete();  //商品标签表

        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 初始化编辑器链接
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath'=>'article'))); // 图片管理
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }

    /*
     *订单首页
     */
    public function index(){
        $begin = date('Y/m/d',(time()-30*60*60*24));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('timegap',$begin.'-'.$end);
        $this->display();
    }

    /*
     *Ajax订单首页
     */
    public function ajaxindex(){
        $orderLogic = new IntegralOrderLogic();
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');
        $condition['parent_sn'] = ["neq","0"];
        $count = M('integral_order')->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =  urlencode($val);
        }
        $show = $Page->show();
        //获取订单列表

        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);

        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display('ajaxindex'.($condition['is_groupbuy'] > 0 ? $condition['is_groupbuy'] : ''));
    }

    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id)
    {
        $orderLogic = new IntegralOrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        // p($order);die;

        $orderGoods = $orderLogic->getOrderGoods($order['goods_id']);
        // p($orderGoods);
        $button = $orderLogic->getOrderButton($order);
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
            if($val['goods_num']>1){
                $split = 1;
            }
        }
        $this->assign('split',$split);
        $this->assign('button',$button);
        $this->display();
    }

    /**
     * 点击去发货
     */
    public function delivery_info(){
        $config = tpCache('shopping');
        $order_id = I('order_id');
        $orderLogic = new IntegralOrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order['goods_id']);

        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list', $shipping_list);
        $this->assign('config', $config);
        $this->display();
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new IntegralOrderLogic();
        $data = I('post.');
        $res = $orderLogic->deliveryHandle($data);
        if($res){
            $this->success('操作成功',U('Admin/Integral/delivery_info',array('order_id'=>$data['order_id'])));
        }else{
            $this->success('操作失败',U('Admin/Integral/delivery_info',array('order_id'=>$data['order_id'])));
        }
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){
        $orderLogic = new IntegralOrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');
        if($action && $order_id){

            $order = $orderLogic->getOrderInfo($order_id);

            try{
                $a = $orderLogic->orderProcessHandle($order_id,$action);
                $res  = true;
            }catch(\Exception $e)
            {
                $this->error($e->getMessage());
            }


            if($res && $a){
                exit(json_encode(array('status' => 1,'msg' => '操作成功')));
            }else{
                exit(json_encode(array('status' => 0,'msg' => '操作失败')));
            }
        }else{
            $this->error('参数错误',U('Admin/Integral/detail',array('order_id'=>$order_id)));
        }
    }

}
